﻿using System;
using UnityEngine;

namespace Framework
{
    public abstract class View3D : ViewLoader
    {
        public IModule BelongModule { get; private set; }

        public virtual void PreInit(IModule belongModule, IEventDispatcher eventDispatcher, ILoader resLoader, IModuleEventDispatcher moduleEventDispatcher)
        {
            BelongModule = belongModule;

            SetEventDispatcher(eventDispatcher, moduleEventDispatcher);
            
            _resLoader = resLoader;

            modulePath = "Bundles/Module/" + belongModule.moduleName + "/";
            
            Log.Debug("View PreInit");

            Init();
        }
        
        /// <summary>
        /// 初始化UI,关联Unity组件
        /// </summary>
        protected abstract void Init();

        /// <summary>
        /// 在场景根节点下加载View3D
        /// </summary>
        /// <param name="path"></param>
        /// <param name="view">要绑定的脚本</param>
        public View3D AddView3D(string path, Type view)
        {
            GameObject go = LoadGameObject(modulePath+path, true);
            View3D component = go.AddScriptComponent(view) as View3D;
            BelongModule.ConnectView3D(component);
            return component;
        }

        public T AddChildView<T>(string path, int siblingIndex = -1) where T:View
        {
            GameObject go = LoadGameObject(path, true);
            View component = (View)go.AddScriptComponent(typeof(T));
            BelongModule.ConnectView(component);
            component.transform.SetParent(transform, false);
            if(siblingIndex >= 0)
            {
                component.transform.SetSiblingIndex(siblingIndex);
            }
            return (T)component;
        }
    }
}